<template>
  <div>
    <van-popup
        v-model="dialogVisible"
        title="地图选址"
        position="bottom" :style="{ height: '80%' }"
    >
      <div id="container"></div>
      <div id="myPageTop">
        <van-field v-model="keyword" placeholder="请输入地址" size="small">
          <template #button>
            <van-button size="small" type="primary" @click="search" icon="search"></van-button>
          </template>
        </van-field>
        <div id="panel"/>
      </div>
      <div class="p-footer">
        <van-button @click="dialogVisible=false" style="flex: 1;height: 38px" round>
          取消
        </van-button>
        <van-button
            style="flex: 1;height: 38px"
            round
            type="primary"
            @click="handleConfirm"
        >
          确定
        </van-button>
      </div>
    </van-popup>
  </div>
</template>

<script>
import AMaps from "@/utils/AMaps";

export default {
  data() {
    return {
      inputValue: '',
      dialogVisible: false,
      newMap: null,
      keyword: ''
    }
  },
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  watch: {
    value(val) {
      this.inputValue = val
    }
  },
  mounted() {
    this.inputValue = this.value
  },
  methods: {
    search() {
      this.newMap.search(this.keyword)
    },
    showModal() {
      this.dialogVisible = true
      this.$nextTick(() => {
        this.newMap = new AMaps({
          dom: 'container',
        });
        this.newMap.initMap()
      })
    },
    handleConfirm() {
      let addressInfo = this.newMap.getAddress()
      this.inputValue = addressInfo.address
      this.$emit('input', this.inputValue)
      this.$emit('change', {...addressInfo})
      this.dialogVisible = false
    }
  },
  unmounted() {
    this.map?.destroy();
  },
}
</script>
<style scoped>
#container {
  padding: 0px;
  margin: 0px;
  width: 100%;
  height: 500px;
}

#myPageTop {
  position: absolute;
  top: 5px;
  right: 10px;
  font-family: "Microsoft Yahei", Pinghei;
  font-size: 14px;
  background: none 0px 0px repeat scroll rgb(255, 255, 255);
  border-width: 1px;
  border-style: solid;
  border-color: rgb(204, 204, 204);
  border-image: initial;
  margin: 10px auto;
}

#panel {
  background-color: white;
  max-height: 300px;
  overflow-y: auto;
}

.p-footer {
  background: #ffffff;
  position: fixed;
  bottom: 0;
  z-index: 1100;
  width: 100%;
  box-sizing: border-box;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 16px;
  gap: 10px;
}
</style>
